import Vue from 'vue'
import Vuex from 'vuex'
import {myRequest} from '@/common/js/request'
import API from '@/common/js/api'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		token: '',
		userInfo: {},
		timerIdent: false,//全局1s定时器，只在全局开启一个，所有需要定时执行的任务监听该值即可，无需额外开启
		cartCount: 0, //购物车数量
		fromPath:''
	},
	getters: {
		hasLogin(state){
			return !!state.token;
		}
	},
	mutations: {
		//更新state数据
		setStateAttr(state, param){
			if(param instanceof Array){
				for(let item of param){
					state[item.key] = item.val;
				}
			}else{
				state[param.key] = param.val;
			}
		},
		//更新token
		setToken(state, data){
			state.token = data;
			uni.setStorageSync('userToken', data);
			this.dispatch('getUserInfo'); //更新用户信息
		},
		//退出登录
		logout(state){
			state.token = '';
			uni.removeStorageSync('userToken');
			// uni.$emit('refreshCart');//刷新购物车
			setTimeout(()=>{
				state.userInfo = {};
			}, 1100)
			uni.navigateTo({
				url: '/pages/login/login'
			})
		},
		// 跳转登录前页面
		setFromPath(state, data){
			state.fromPath = data;
		}
	},
	actions: {
		//更新用户信息
		async getUserInfo({state, commit}){
			const res = await myRequest({
				url: API.getUserInfo,
				methods: 'GET'
			});
			if(res.code == 200){
				const userInfo = res.data;
				commit('setStateAttr', {
					key: 'userInfo',
					val: userInfo
				});
			}
		},
	}
}) 


export default store
